//
//  CustomTabBarVC.m
//  LeagueOfLegend
//
//  Created by cc on 14-7-8.
//  Copyright (c) 2014年 cc. All rights reserved.
//
#define SLIDE_ANIMATION_DURATION 0.35
#import "CustomTabBarVC.h"

@interface CustomTabBarVC ()

@end

@implementation CustomTabBarVC
@synthesize previousNavViewController = _previousNavViewController;
@synthesize viewControllers = _viewControllers;
@synthesize selectedIndex = _selectedIndex;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        _selectedIndex = -1;
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    _normalImageArray = [[NSArray alloc] initWithObjects:@"zhoumian",@"update",@"yuezhan",@"video", nil];
    _highlightedImageArray = [[NSArray alloc] initWithObjects:@"zhoumianFinish",@"updateFinish",@"yuezhanFinish",@"videoFinish", nil];
    [self loadMyTabBarView];
    if (_selectedIndex == -1)
	{
        //用self.赋值默认会调set方法
		self.selectedIndex = 0;
	}
	else
	{
        //用self.赋值默认会调set方法
		self.selectedIndex = _selectedIndex;
	}
}

- (void)loadMyTabBarView
{
    _tabBarView = [[UIView alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height - 49, self.view.frame.size.width, 49)];
    for (int i = 0; i < 4; i++)
    {
        UIButton *tabBarBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        tabBarBtn.frame = CGRectMake(i * (self.view.frame.size.width/4), 0, self.view.frame.size.width/4, 49);
        tabBarBtn.backgroundColor = [UIColor clearColor];
        tabBarBtn.tag = i + 200;
        [tabBarBtn setImage:[UIImage imageNamed:[_normalImageArray objectAtIndex:i]] forState:UIControlStateNormal];
        //        NSLog(@"%@",[_highlightedImageArray objectAtIndex:1]);
        [tabBarBtn setImage:[UIImage imageNamed:[_normalImageArray objectAtIndex:i]] forState:UIControlStateHighlighted];
        [tabBarBtn addTarget:self action:@selector(changeViewController:) forControlEvents:UIControlEventTouchUpInside];
        [_tabBarView addSubview:tabBarBtn];
    }
    [self.view addSubview:_tabBarView];
}

- (void)setSelectedIndex:(int)aIndex
{
    if (_selectedIndex == aIndex)
    {
        return;
    }
    if (_selectedIndex >= 0)
    {
        //如果索引值改变了需要做操作
        /*
         安全性判断
         如果_seletedIndex表示当前显示的有视图
         需要把原来的移除掉，然后把对应的TabBar按钮设置为正常状态
         */
        UIViewController *priciousViewController = [_viewControllers objectAtIndex:_selectedIndex];
        [priciousViewController.view removeFromSuperview];
        
        UIButton *priciousBtn = (UIButton *)[self.view viewWithTag:(_selectedIndex + 200)];
        [priciousBtn setImage:[UIImage imageNamed:[_normalImageArray objectAtIndex:_selectedIndex]] forState:UIControlStateNormal];
        
    }
    _selectedIndex = aIndex;
    
    UIButton *currentBtn = (UIButton *)[self.view viewWithTag:(aIndex + 200)];
    [currentBtn setImage:[UIImage imageNamed:[_highlightedImageArray objectAtIndex:aIndex]] forState:UIControlStateNormal];
    
    UIViewController *currentViewController = [_viewControllers objectAtIndex:aIndex];
    
    if ([currentViewController isKindOfClass:[UINavigationController class]])
	{
        ((UINavigationController *)currentViewController).delegate = self;
    }
    //    currentViewController.view.frame = CGRectMake(0, 0, 320, self.view.frame.size.height-49-64);
    [self.view addSubview:currentViewController.view];
    [self.view sendSubviewToBack:currentViewController.view];
    
}

- (void)changeViewController:(id)sender
{
    UIButton *btn = (UIButton *)sender;
    //    NSLog(@"btn.tag==>>%d",btn.tag);
    int index = btn.tag - 200;
    self.selectedIndex = index;
    
}

#pragma mark -
#pragma mark UINavigationControllerDelegate

- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated
{
    //NSLog(@"vc is %@",viewController);
    /*
     第一次加载根视图:previousNavViewController当前导航控制器里面的视图控制器数组
     之后显示视图:previousNavViewController操作前的视图控制器数组
     */
	if (!_previousNavViewController)
	{
        //导航控制器中的视图数组
		self.previousNavViewController = navigationController.viewControllers;
	}
	
	/*
     是否为压栈的标记，初始化为NO
     如果原来的控制器数不大于当前导航的视图控制器数表示是压栈
     */
	BOOL isPush = NO;
	if ([_previousNavViewController count] <= [navigationController.viewControllers count])
	{
		isPush = YES;
	}
	
    /*
     上一个视图控制器当压栈的时候底部条是否隐藏
     当前视图控制器当压栈的时候底部条是否隐藏
     这两个视图控制器有可能是同一个
     */
	BOOL isPreviousHidden = [[_previousNavViewController lastObject] hidesBottomBarWhenPushed];
	BOOL isCurrentHidden = viewController.hidesBottomBarWhenPushed;
    //    [[navigationController.viewControllers lastObject] hidesBottomBarWhenPushed]
	
    //重新记录当前导航器中的视图控制器数组
	self.previousNavViewController = navigationController.viewControllers;
	
    /*
     如果状态相同不做其他操作
     如果上一个显示NO，这个隐藏YES，则隐藏TabBar
     如果上一个隐藏YES，这个显示NO，则显示TabBar
     */
	if (!isPreviousHidden && !isCurrentHidden)
	{
		return;
	}
	else if(isPreviousHidden && isCurrentHidden)
	{
		return;
	}
	else if(!isPreviousHidden && isCurrentHidden)
	{
		//隐藏tabbar 压栈
		[self hideTabBar:isPush ? SlideDirectionLeft : SlideDirectionRight  animated:animated];
	}
	else if(isPreviousHidden && !isCurrentHidden)
	{
		//显示tabbar 出栈
		[self showTabBar:isPush ? SlideDirectionLeft : SlideDirectionRight animated:animated];
	}
	
}

/*
 显示底部TabBar相关
 需要重置当前视图控制器View的高度为整个屏幕的高度-TabBar的高度
 */
- (void)showTabBar:(SlideDirection)direction animated:(BOOL)isAnimated
{
	//根据压栈还是出栈设置TabBar初始位置
	CGRect tempRect = _tabBarView.frame;
	tempRect.origin.x = self.view.bounds.size.width * ( (direction == SlideDirectionRight) ? -1 : 1);
	_tabBarView.frame = tempRect;
	
    //执行动画
	[UIView animateWithDuration:isAnimated ? SLIDE_ANIMATION_DURATION : 0 delay:0 options:0 animations:^
	 {
		 //动画效果
		 CGRect tempRect = _tabBarView.frame;
		 tempRect.origin.x = 0;
		 _tabBarView.frame = tempRect;
		 
	 }
                     completion:^(BOOL finished)
	 {
         //         //动画结束时
         //         //重置当前视图控制器View的高度为整个屏幕的高度-TabBar的高度
         //		 UIViewController *currentViewController = [_viewControllers objectAtIndex:_selectedIndex];
         //
         //		 CGRect viewRect = currentViewController.view.frame;
         //		 viewRect.size.height = self.view.bounds.size.height - 43;
         //		 currentViewController.view.frame = viewRect;
	 }];
}

/*
 隐藏底部TabBar相关
 需要重置当前视图控制器View的高度为整个屏幕的高度
 */
- (void)hideTabBar:(SlideDirection)direction animated:(BOOL)isAnimated
{
    //    //获得当前视图控制器
    //	UIViewController *currentViewController = [_viewControllers objectAtIndex:_selectedIndex];
    //	//重置高度
    //	CGRect viewRect = currentViewController.view.frame;
    //	viewRect.size.height = self.view.bounds.size.height;
    //	currentViewController.view.frame = viewRect;
	
    //设置TabBar的位置
	CGRect tempRect = _tabBarView.frame;
	tempRect.origin.x = 0;
	_tabBarView.frame = tempRect;
	
    //采用Block的形式开启一个动画
	[UIView animateWithDuration:isAnimated ? SLIDE_ANIMATION_DURATION : 0 delay:0 options:0 animations:^(void)
     {
         //根据压栈还是出栈设置动画效果
		 CGRect tempRect = _tabBarView.frame;
		 tempRect.origin.x = self.view.bounds.size.width * (direction == SlideDirectionLeft ? -1 : 1);
		 _tabBarView.frame = tempRect;
		 
     }
                     completion:^(BOOL finished){}
     ];
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
 {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
